#
# Copyright (c) 2008 Andreas Blixt <andreas@blixt.org>
# Project homepage: <http://tack-web.googlecode.com/>
#

import wsgiref.handlers

from google.appengine.ext import db, webapp

import demjson, md5, time

class Game(db.Model):
    authkey = db.StringProperty(required = True)
    title = db.StringProperty(required = True)
    author = db.StringProperty()
    description = db.TextProperty()
    data = db.TextProperty(required = True)

class TackService(webapp.RequestHandler):
    def generate_authkey(self):
        authkey = md5.new(str(time.time())).hexdigest()[0:8]
        while Game.gql('WHERE authkey = :1', authkey).count() > 0:
            authkey = md5.new(authkey + str(time.time())).hexdigest()[0:8]

        return authkey

    def out(self, text):
        self.response.out.write(text)

    def post(self):
        action = self.request.params['action']
        if action == 'get':
            game = Game.get_by_id(int(self.request.str_params['gameId']))

            if game:
                self.out(demjson.encode({
                    'result': 'success',
                    'gameId': game.key().id(),
                    'game': demjson.decode(game.data)
                }))
            else:
                self.out(demjson.encode({
                    'result': 'error',
                    'error': 'The game could not be loaded.'
                }))
            
        elif action == 'set':
            try:
                json_object = demjson.decode(self.request.str_params['data'])
                json = demjson.encode(json_object)

                if 'authKey' in self.request.str_params:
                    game = Game.gql('WHERE authkey = :1', self.request.str_params['authKey']).get()
                else:
                    game = None

                if game:
                    game.title = json_object['title']
                    game.data = json
                    game.description = json_object['description']
                    game.author = json_object['author']
                else:
                    game = Game(authkey = self.generate_authkey(),
                                title = json_object['title'],
                                data = json,
                                description = json_object['description'],
                                author = json_object['author'])

                game.put()

                self.out(demjson.encode({
                    'result': 'success',
                    'authKey': game.authkey,
                    'gameId': game.key().id()
                }))
                
            except:
                self.out(demjson.encode({
                    'result': 'error',
                    'error': 'Invalid game data.'
                }))

def main():
    application = webapp.WSGIApplication([
        ('/server.php', TackService)
    ])
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()
